﻿using System.IO;
using System.Text;

namespace GMS.NET.Core.Tools
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileTool
    {
        /// <summary>
        /// 寻找文件夹下的指定文件
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string[] FindFilesInFolder(string folderPath, string fileName)
        {
            // Search for files that match the specified file name in the specified folder
            string[] matchingFiles = Directory.GetFiles(folderPath, fileName, SearchOption.AllDirectories);

            return matchingFiles;
        }
        /// <summary>
        /// 指定文件夹下创建文件夹
        /// </summary>
        /// <param name="ThisDirectory"></param>
        /// <param name="CreateDirectory"></param>
        public static string ThisDirectoryCreateDirectory(string ThisDirectory, string CreateDirectory)
        {
            string newFolderPath = Path.Combine(ThisDirectory, CreateDirectory);
            Directory.CreateDirectory(newFolderPath);
            return newFolderPath;
        }

        private static readonly object lockObject = new object();

        /// <summary>
        /// 写入文本文档
        /// </summary>
        /// <param name="FilePath">文件名称可带路径 例 /logs/log.txt</param>
        /// <param name="ContentText">文件内容</param>
        /// <returns></returns>
        public static Task WriteText(string FilePath, string ContentText)
        {
            // 获取项目根目录
            string rootPath = App.HostEnvironment.ContentRootPath;

            // 去掉开头的所有斜杠 '/'
            while (FilePath.Length > 0 && FilePath[0] == '/')
            {
                FilePath = FilePath.TrimStart('/');
            }

            // 拼接文件路径
            string filePath_ = Path.Combine(rootPath, FilePath);

            string directoryPath = Path.GetDirectoryName(filePath_)!;

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            lock (lockObject)
            {
                // 使用using语句确保StreamWriter在使用后被正确释放
                using (StreamWriter writer = new StreamWriter(filePath_, true))
                {
                    // 写入每行的内容
                    writer.WriteLine($"{DateTime.Now}-{ContentText}");
                    // 在每行写入后换行
                    writer.WriteLine();
                }
            }
            return Task.CompletedTask;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class ApiCodeTool
    {
        /// <summary>
        ///  在.cs文件中插入方法
        ///  使用前请格式化cs文件
        /// </summary>
        /// <param name="csbodyContent"></param>
        /// <param name="sb"></param>
        /// <param name="indentLength"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string ModifyAndAddInterfaceMethod(string csbodyContent, StringBuilder sb, int indentLength = 2)
        {
            string[] lines = csbodyContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            int lastBraceIndex = Array.LastIndexOf(lines, "}");
            if (lastBraceIndex < 0)
            {
                throw new Exception("No closing brace found in the file.");
            }

            int insertionIndex = lastBraceIndex - 1;

            // 构建要新增的接口方法行（包括多行内容）

            string Linet = "";
            for (int i = 0; i < indentLength; i++) { Linet += "\t"; }

            string[] sblines = sb.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            for (int i = 0; i < sblines.Length; i++)
            {
                sblines[i] = $"{Linet}{sblines[i]}";
            }

            sb.Clear();

            foreach (string sbline in sblines)
            {
                sb.AppendLine(sbline);
            }

            string newMethodLines = sb.ToString();

            // 在 content 中插入新增的接口方法行（在倒数第二个 `}` 的上一行）
            string newContent = string.Join(Environment.NewLine, lines.Take(insertionIndex));
            newContent += Environment.NewLine + newMethodLines;
            newContent += string.Join(Environment.NewLine, lines.Skip(insertionIndex));

            return newContent;
        }
    }
}
